package com.dqx.haoqiu.mvp.utils;

import android.content.Context;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.DeleteObjectRequest;
import com.alibaba.sdk.android.oss.model.DeleteObjectResult;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;

/**
 * 阿里云OSS文件上传工具类
 */
public class OssUploadFile {
    private OSS oss;
    //凭证提供者
    private OSSCredentialProvider credentialProvider;
    //配置
    private ClientConfiguration conf;
    //回调
    private AliyunUploadCallback callback;
    //异步任务
    OSSAsyncTask ossAsyncTask;

    public OssUploadFile(AliyunUploadCallback aliyunUploadView) {
        this.callback = aliyunUploadView;
    }

    /**
     * 上传文件
     *
     * @param context        上下文
     * @param AccessKeyId    存取键（找后端拿）
     * @param SecretKeyId    密钥（找后端拿）
     * @param SecurityToken  token（找后端拿）
     * @param endpoint       OSS服务地址（找后端拿）
     * @param bucketName     桶名，用于存储图片或文件的桶，类似文件仓库（找后端拿）
     * @param fileName       文件名
     * @param uploadFilePath 文件路径
     */
    public void UploadFile(Context context, String AccessKeyId, String SecretKeyId, String SecurityToken,
                           String endpoint, String bucketName, String fileName, String uploadFilePath) {
        //凭证
        credentialProvider = new OSSStsTokenCredentialProvider(AccessKeyId, SecretKeyId, SecurityToken);

        //配置
        conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000);//连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000);//socket超时，默认15秒
        conf.setMaxConcurrentRequest(5);//最大并发请求数，默认5个
        conf.setMaxErrorRetry(2);//失败后最大重试次数，默认2次
        oss = new OSSClient(context, endpoint, credentialProvider, conf);
        //创建上传请求
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, uploadFilePath);
        //异步上传时可以设置进度回调。
        putObjectRequest.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {

            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                if (callback != null)
                    callback.onProgress(currentSize, totalSize);
            }
        });
        //异步执行上传任务
        ossAsyncTask = oss.asyncPutObject(putObjectRequest, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {

            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                callback.UploadSuccess(oss.presignPublicObjectURL(bucketName, fileName));
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                //本地异常，如网络异常等
                if (clientExcepion != null) {
                    callback.UploadDefeated(clientExcepion.getMessage());
                }
                // 服务异常
                if (serviceException != null) {
                    callback.UploadDefeated(serviceException.getMessage());
                }
            }
        });
    }

    /**
     * 删除文件
     *
     * @param context       上下文
     * @param AccessKeyId   存取键（找后端拿）
     * @param SecretKeyId   密钥（找后端拿）
     * @param SecurityToken Token（找后端拿）
     * @param endpoint      OSS服务地址（找后端拿）
     * @param bucketName    桶名（找后端拿）
     * @param fileName      文件名
     */
    public void DeleteFile(Context context, String AccessKeyId, String SecretKeyId, String SecurityToken,
                           String endpoint, String bucketName, String fileName) {
        //凭证
        credentialProvider = new OSSStsTokenCredentialProvider(AccessKeyId, SecretKeyId, SecurityToken);
        //配置
        conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000);// 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000);// socket超时，默认15秒
        conf.setMaxConcurrentRequest(5);// 最大并发请求数，默认5个
        conf.setMaxErrorRetry(2);// 失败后最大重试次数，默认2次
        oss = new OSSClient(context, endpoint, credentialProvider, conf);
        //创建删除请求
        DeleteObjectRequest delete = new DeleteObjectRequest(bucketName, fileName);
        //异步执行删除任务
        ossAsyncTask = oss.asyncDeleteObject(delete, new OSSCompletedCallback<DeleteObjectRequest, DeleteObjectResult>() {

            @Override
            public void onSuccess(DeleteObjectRequest request, DeleteObjectResult result) {

            }

            @Override
            public void onFailure(DeleteObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                //本地异常
                if (clientExcepion != null) {

                }
                //服务异常
                if (serviceException != null) {

                }
            }
        });
    }

    /**
     * 取消任务
     */
    public void cancel() {
        if (ossAsyncTask != null && !ossAsyncTask.isCompleted())
            ossAsyncTask.cancel();
    }

    /**
     * 自定义回调接口
     */
    public interface AliyunUploadCallback {
        //上传成功
        void UploadSuccess(String url);

        //上传失败
        void UploadDefeated(String error);

        //上传进度
        void onProgress(long currentSize, long totalSize);
    }

}